package ca.scotthyndman.as2haxe.dom;

import java.util.ArrayList;
import java.util.List;

import ca.scotthyndman.as2haxe.dom.visitor.IVisitor;

/**
 * Represents a function declared inline.
 */
public class ASFunctionExpression extends ASExpression {

	/**
	 * The "function" structural property of this node type.
	 * 
	 * @since 3.0
	 */
	public static final ASChildPropertyDescriptor FUNCTION_PROPERTY = new ASChildPropertyDescriptor(
			ASFunctionExpression.class, "function", ASFunction.class, true);

	/**
	 * A list of property descriptors (element type:
	 * {@link ASPropertyDescriptor}), or null if uninitialized.
	 */
	private static final List<ASPropertyDescriptor> PROPERTY_DESCRIPTORS;

	static {
		List<Object> properyList = new ArrayList<Object>(2);
		createPropertyList(ASFunctionExpression.class, properyList);
		addProperty(FUNCTION_PROPERTY, properyList);
		PROPERTY_DESCRIPTORS = reapPropertyList(properyList);
	}

	/**
	 * Returns a list of structural property descriptors for this node type.
	 * Clients must not modify the result.
	 * 
	 * @return a list of property descriptors
	 */
	public static List<ASPropertyDescriptor> propertyDescriptors() {
		return PROPERTY_DESCRIPTORS;
	}

	private ASFunction function;

	/**
	 * Constructs a new instance of ASFunctionExpression
	 * 
	 * @param ast
	 *            The abstract syntax tree that owns this element
	 */
	public ASFunctionExpression(AST ast) {
		super(ast);
	}

	/**
	 * @param function
	 *            the function to set
	 */
	public void setFunction(ASFunction function) {
		if (function == null) {
			throw new IllegalArgumentException();
		}
		ASTNode oldChild = this.function;
		preReplaceChild(oldChild, function, FUNCTION_PROPERTY);
		this.function = function;
		postReplaceChild(oldChild, function, FUNCTION_PROPERTY);
	}

	/**
	 * @return the function
	 */
	public ASFunction getFunction() {
		return function;
	}

	//
	// ======== INTERNAL GETTER / SETTER
	//

	/*
	 * (omit javadoc for this method) Method declared on ASTNode.
	 */
	final ASTNode internalGetSetChildProperty(
			ASChildPropertyDescriptor property, boolean get, ASTNode child) {
		if (property == FUNCTION_PROPERTY) {
			if (get) {
				return getFunction();
			} else {
				setFunction((ASFunction) child);
				return null;
			}
		}

		// allow default implementation to flag the error
		return super.internalGetSetChildProperty(property, get, child);
	}

	//
	// ======== OVERRIDES
	//

	@Override
	public String toString() {
		return getFunction().toString();
	}

	@Override
	public void accept(IVisitor as2Visitor, boolean recursive) {
		recursive = as2Visitor.visit(this);

		if (recursive) {
			getFunction().accept(as2Visitor, recursive);
		}
	}
}
